#include "device.h"
#include <QDebug>

Device::Device(const QString &ipAddress, const QString &deviceId, QObject *parent)
    : QObject(parent)
    , m_ipAddress(ipAddress)
    , m_deviceId(deviceId)
    , m_webSocketClient(new WebSocketClient(this))
    , m_isLoggedIn(false)
{
    // 连接WebSocket信号和槽
    connect(m_webSocketClient, &WebSocketClient::connectionStateChanged, 
            this, &Device::onWebSocketConnectionStateChanged);
    connect(m_webSocketClient, &WebSocketClient::errorOccurred, 
            this, &Device::onWebSocketError);
    
    // 连接登录相关信号槽
    connect(m_webSocketClient, &WebSocketClient::challengeReceived, 
            this, &Device::onChallengeReceived);
    connect(m_webSocketClient, &WebSocketClient::loginSuccess, 
            this, &Device::onLoginSuccess);
    connect(m_webSocketClient, &WebSocketClient::loginFailed, 
            this, &Device::onLoginFailed);
    
    // 连接网络配置相关信号槽
    connect(m_webSocketClient, &WebSocketClient::networkConfigReceived,
            this, &Device::onNetworkConfigReceived);
    connect(m_webSocketClient, &WebSocketClient::networkConfigSetResult,
            this, &Device::onNetworkConfigSetResult);
    
    // 连接固件升级相关信号槽
    connect(m_webSocketClient, &WebSocketClient::firmwareUploadProgress,
            this, &Device::onFirmwareUploadProgress);
    connect(m_webSocketClient, &WebSocketClient::firmwareUploadComplete,
            this, &Device::onFirmwareUploadComplete);
    connect(m_webSocketClient, &WebSocketClient::firmwareUpgradeStarted,
            this, &Device::onFirmwareUpgradeStarted);
    connect(m_webSocketClient, &WebSocketClient::firmwareUpgradeStatusReceived,
            this, &Device::onFirmwareUpgradeStatusReceived);
    connect(m_webSocketClient, &WebSocketClient::firmwareUpgradeError,
            this, &Device::onFirmwareUpgradeError);
}

Device::~Device()
{
}

void Device::connectToDevice()
{
    QString wsUrl = QString("ws://%1:80/v1/protocol").arg(m_ipAddress);
    qDebug() << "正在连接WebSocket:" << wsUrl;
    m_webSocketClient->connectToServer(wsUrl);
}

void Device::disconnectFromDevice()
{
    m_webSocketClient->disconnectFromServer();
}

bool Device::isConnected() const
{
    return m_webSocketClient->isConnected();
}

void Device::requestChallenge(const QString &username)
{
    m_webSocketClient->requestChallenge(username, m_deviceId);
}

void Device::login(const QString &username, const QString &challenge, 
                  const QString &credential, bool rememberMe)
{
    m_webSocketClient->login(username, challenge, credential, m_deviceId, rememberMe);
}

void Device::getNetworkConfig()
{
    m_webSocketClient->getNetworkConfig();
}

void Device::setNetworkConfig(const QString &interfaceName, bool enable, const QString &mode, 
                             const QString &ipAddress, const QString &netmask, const QString &gateway)
{
    m_webSocketClient->setNetworkConfig(interfaceName, enable, mode, ipAddress, netmask, gateway);
}

void Device::uploadFirmware(int chunkIndex, int totalChunks, const QByteArray &chunkData, 
                           const QString &fileName, qint64 fileSize, 
                           const QString &version, const QString &md5)
{
    m_webSocketClient->uploadFirmware(chunkIndex, totalChunks, chunkData, fileName, fileSize, version, md5);
}

void Device::startFirmwareUpgrade(const QString &version, bool force)
{
    m_webSocketClient->startFirmwareUpgrade(version, force);
}

void Device::getFirmwareUpgradeStatus()
{
    m_webSocketClient->getFirmwareUpgradeStatus();
}

// WebSocket连接状态变化
void Device::onWebSocketConnectionStateChanged(bool connected)
{
    emit connectionStateChanged(m_ipAddress, connected);
    
    if (!connected) {
        // 连接断开时，清除登录状态
        m_isLoggedIn = false;
        m_accessToken.clear();
        m_refreshToken.clear();
        m_userInfo = QJsonObject();
    }
}

// WebSocket错误处理
void Device::onWebSocketError(const QString &errorMessage)
{
    emit errorOccurred(m_ipAddress, errorMessage);
}

// 收到挑战码
void Device::onChallengeReceived(const QString &challenge, int expiresIn)
{
    // 保存挑战码
    m_currentChallenge = challenge;
    emit challengeReceived(m_ipAddress, challenge, expiresIn);
}

// 登录成功
void Device::onLoginSuccess(const QString &accessToken, const QString &refreshToken, const QJsonObject &userInfo)
{
    // 保存令牌和用户信息
    m_accessToken = accessToken;
    m_refreshToken = refreshToken;
    m_userInfo = userInfo;
    m_isLoggedIn = true;
    
    emit loginSuccess(m_ipAddress, accessToken, refreshToken, userInfo);
}

// 登录失败
void Device::onLoginFailed(int errorCode, const QString &errorMessage)
{
    emit loginFailed(m_ipAddress, errorCode, errorMessage);
}

// 网络配置相关槽函数实现
void Device::onNetworkConfigReceived(const QJsonObject &config)
{
    emit networkConfigReceived(m_ipAddress, config);
}

void Device::onNetworkConfigSetResult(bool success, const QString &message)
{
    emit networkConfigSetResult(m_ipAddress, success, message);
}

// 固件升级相关槽函数实现
void Device::onFirmwareUploadProgress(int progress)
{
    emit firmwareUploadProgress(m_ipAddress, progress);
}

void Device::onFirmwareUploadComplete()
{
    emit firmwareUploadComplete(m_ipAddress);
}

void Device::onFirmwareUpgradeStarted(const QString &upgradeId, const QString &status, int estimatedDuration)
{
    emit firmwareUpgradeStarted(m_ipAddress, upgradeId, status, estimatedDuration);
}

void Device::onFirmwareUpgradeStatusReceived(const QString &status, int progress, const QString &message)
{
    emit firmwareUpgradeStatusReceived(m_ipAddress, status, progress, message);
}

void Device::onFirmwareUpgradeError(const QString &errorMessage)
{
    emit firmwareUpgradeError(m_ipAddress, errorMessage);
}